// pages/index/index.js
import { query, queryByPage, count } from '../../utils/db'
const app = getApp()

Page({
  data: {
    disableJoin: true,
    pageEnd: false,
    currPage: 0,
    showAuth: false,
    entered: false,
    personTotal: 0,
    threeClasses: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    grade: [],
    allClassMates: [],
    currClasses: [],
    currClassIdx: 0,
    avatarUrl: '',
    userInfo: null,
  },
  onLoad() {
    const self = this
    this.onGetOpenid()
    this.getPersonCount()
    this.getPersonByPage(this.data.currPage)
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
        } else { }
      },
      complete: () => { this.getUserInfo() },
    })
  },
  getPersonCount() {
    count('entryForms', {})
    .then(total => {
      this.setData({ personTotal: total })
    })
    const CLASS_COUNT = 10
    const list = new Array(CLASS_COUNT).fill(1)
    list.forEach((item, index) => {
      count('entryForms', { 'klass.2': index + 1 })
      .then(total => {
        this.setData({ [`threeClasses[${index}]`]: total })
      })
    })
  },
  getPersonByPage(page) {
    const LIMIT = 20
    if (this.data.pageEnd) { 
      return
    }
    queryByPage('entryForms', {}, page, LIMIT).then(res => {
      if (res.length < LIMIT) {
        this.setData({ pageEnd: true })
      }
      const oldCount = this.data.allClassMates.length
      res.forEach((person, index) => {
        this.setData({
          [`allClassMates[${oldCount + index }]`]: person,
          [`currClasses[${oldCount + index }]`]: person,
        })
      })
    })
  },
  onPullDownRefresh() {
    this.getPersonCount()
    this.setData({
      currClasses: [],
      allClassMates: [],
      currPage: 0,
      pageEnd: false,
    })
    this.getPersonByPage(0)
    wx.stopPullDownRefresh()
  },
  onReachBottom() {
    this.setData({ currPage: this.data.currPage + 1 })
    this.getPersonByPage(this.data.currPage)
  },

  getUserInfo() {
    wx.getUserInfo({
      success: res => {
        this.setData({
          avatarUrl: res.userInfo.avatarUrl,
          userInfo: res.userInfo,
        })
        app.globalData.avatarUrl = res.userInfo.avatarUrl
        app.globalData.userInfo = res.userInfo
        this.setData({ showAuth: false })
      },
      fail: err => {
        console.log('获取用户信息失败：', err)
        this.setData({ showAuth: true })
      }
    })
  },

  onJoin() {
    wx.navigateTo({ url: `../join/join` })
  },

  onTapClass(e) {
    const index = e.currentTarget.dataset.index
    wx.navigateTo({ url: `../klass/klass?index=${index}` })
  },
  onListAllClasses() {
    this.setData({
      currClassIdx: 0,
      currClasses: this.data.allClassMates,
    })
  },
  onShareAppMessage(Object) {
    return {
      title: '贵溪一中99届20年后再相会',
      path: '/pages/index/index',
      imageUrl: 'http://qiniu.awoo.co/share-mini.jpg',
    }
  },
  getEntered(_openid) {
    query('entryForms', { _openid }).then(res => {
      const entered = !!res.length
      app.globalData.entered = entered
      app.globalData.formid = res[0] && res[0]._id
      this.setData({ disableJoin: false, entered: entered })
    })
  },
  onGetOpenid() {
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        app.globalData._openid = res.result.openid
        this.getEntered(res.result.openid)
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })
  },
  onImgTap(e) {
    query('entryForms', { avatarID: e.detail }).then(res => {
      wx.navigateTo({
        url: `/pages/personPage/personPage?openid=${res[0]._openid}`
      })
    })
  }
})